package com.example.springflowable.utils;

import com.alibaba.fastjson.JSONObject;
import liquibase.pro.packaged.O;
import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;

import org.dom4j.io.XMLWriter;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @Classname XmlUtils
 * @Description TODO
 * @Date 2022/5/9 20:16
 * @Created by XiongXiong
 * @Author: X.I.O
 */
public class XmlUtils {

    public static void main(String[] args) throws IOException, DocumentException, Exception {
        List<Element> elements=readTest();
        Test3(elements);
        //wirte();
        // read();
    }

    public static void Test3(List<Element> elements){
        //找到开始
        Element element=elements.stream().filter(e->{
            return "startEvent".equals(e.getName());
        }).findFirst().orElse(null);

        if(element==null){
            return;
        }
        String startId=element.attributeValue("id");
        System.out.println(startId);
        List<Map<String,Object>> objects=new ArrayList<>();
        getTest(elements,objects,element.attributeValue("id"),"id");
        for (int i = 0; i < objects.size() ; i++) {
            System.out.println(JSONObject.toJSONString(objects.get(i)));
        }
    }

    public static void getTest(List<Element> elements,List<Map<String,Object>> maps,String id,String type){
        if("id".equals(type)){
            List<Element> els=sqlsourceRefNodeList(elements,maps,id);
            if(els!=null){
                for (Element elsValue : els) {
                    System.out.println(elsValue.getName());
                    String elId=elsValue.attributeValue("targetRef");
                    System.out.println(elId);
                    getTest(elements,maps,elId,"sourceRef");
                }
            }
        }else {
            List<Element> els=sqlTargetRefNodeList(elements,maps,id);
            if(els != null){
                for (Element elsValue : els) {
                    String elId=elsValue.attributeValue("id");
                    getTest(elements,maps,elId,"id");
                }
            }
        }
    }

    public static List<Element> sqlTargetRefNodeList(List<Element> elements,List<Map<String,Object>> objectList,String nodeId){
        List<Element> elementList=elements.stream().filter(e->{
            if(!"".equals(e.attributeValue("id")) && !"null".equals(e.attributeValue("id"))){
                String id=e.attributeValue("id");
                if(id.equals(nodeId)){
                    return true;
                }
            }
            return false;
        }).collect(Collectors.toList());
        for (Element element : elementList) {
            Map<String, Object> map=new HashMap<>();
            map.put("name",element.getName());
            objectList.add(map);
        }
        return elementList;
    }


    public static List<Element> sqlsourceRefNodeList(List<Element> elements,List<Map<String,Object>> objectList,String nodeId){
        List<Element> elementList=elements.stream().filter(e -> {
            if(!"".equals(e.attributeValue("sourceRef")) && !"null".equals(e.attributeValue("sourceRef"))){
                String sourceRefId=e.attributeValue("sourceRef");
                if(sourceRefId.equals(nodeId)){
                    return true;
                }
            }
            return false;
        }).collect(Collectors.toList());
        for (Element element : elementList) {
            Map<String, Object> map=new HashMap<>();
            map.put("name",element.getName());
            objectList.add(map);
        }
        return elementList;
    }

    public static void Test2() throws Exception{
        List<Element> elements=readTest();
        for (Element element : elements) {
            System.out.println(element.getName());
            System.out.println(element.attributeValue("id"));
            if(!"startEvent".equals(element.getName()) && !"endEvent".equals(element.getName())){
                System.out.println(element.getName());
            }
            if("userTask".equals(element.getName())){
                System.out.println(element.attributeValue("assignee")+" == "+element.attributeValue("name"));
            }
            if("sequenceFlow".equals(element.getName())){
                System.out.println(element.attributeValue("sourceRef")+element.getName()+" 线条 "+element.attributeValue("targetRef"));
            }
            if("exclusiveGateway".equals(element.getName())){

            }
            if(element.getName().equals("")){
                if ("sequenceFlow".equals(element.getName())) {

                }
            }
        }
    }

    public static void wirte() {
        Document document = DocumentHelper.createDocument();
        Element rss = document.addElement("bookstore");
        Element book = rss.addElement("book");
        book.addAttribute("id", "1001");
        book.addAttribute("flowable:key", "12333");
        Element name = book.addElement("name");
        name.setText("java编程思想");
        OutputFormat format = OutputFormat.createPrettyPrint();
//设置编码格式为gbk，默认utf-8
        format.setEncoding("gbk");
        try {
            File f = new File("D:\\Users\\X.I.O\\code\\spring-flowable\\src\\main\\resources\\processes\\book.xml");
            XMLWriter writer = new XMLWriter(new FileOutputStream(f), format);
            //设置是否转义。默认true，代表转义
            writer.setEscapeText(false);
            writer.write(document);
            writer.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public static List<Element> readTest() throws Exception{
        SAXReader saxReader = new SAXReader(); //SAXReader
        Document document = saxReader.read("D:\\Users\\X.I.O\\code\\spring-flowable\\src\\main\\resources\\processes\\ask_for_overtime.bpmn20.xml");
        Element rootElement = document.getRootElement();
        Iterator iter = rootElement.elementIterator();
        List<Element> elements=new ArrayList<>();
        while (iter.hasNext()) {
            Element element = (Element) iter.next();
            if ("process".equals(element.getName())) {
                Iterator process = element.elementIterator();
                while (process.hasNext()) {
                    Element node = (Element) process.next();
                    if ("startEvent".equals(node.getName())) {
//                        String formKey = node.attributeValue("assignee");
//                        Attribute attribute = node.attribute("formKey");
//                        attribute.setValue("123456");
                    }
                    elements.add(node);
                }
                //指定文件输出的位置
            }
        }
        return elements;
    }

    public static void test() throws Exception {
        SAXReader saxReader = new SAXReader(); //SAXReader
        Document document = saxReader.read("D:\\Users\\X.I.O\\code\\spring-flowable\\src\\main\\resources\\processes\\ask_for_overtime.bpmn20.xml");
        Element rootElement = document.getRootElement();
        Iterator iter = rootElement.elementIterator();
        while (iter.hasNext()) {
            Element element = (Element) iter.next();
            if ("process".equals(element.getName())) {
                String name = element.attributeValue("name");
                System.out.println(name);
                Iterator process = element.elementIterator();
                while (process.hasNext()) {
                    Element node = (Element) process.next();
                    if ("startEvent".equals(node.getName())) {
                        String formKey = node.attributeValue("assignee");
                        Attribute attribute = node.attribute("formKey");
                        attribute.setValue("123456");
                    }
                    if ("sequenceFlow".equals(node.getName())) {
                        Iterator seqs = node.elementIterator();
                        String id = node.attributeValue("id");
                        if ("sid-6cb09a5b-778a-4280-af49-9a557eba7e82".equals(id)) {
                            while (seqs.hasNext()) {
                                Element se = (Element) seqs.next();
                                se.setText("<![CDATA[${checkResult=='驳回111'}]]>");
                                System.out.println(se.getName());
                                System.out.println(se.getText());
                            }
                        }

                    }
                    System.out.println(node.getName());
                }
                //指定文件输出的位置
                FileOutputStream out = new FileOutputStream("D:\\Users\\X.I.O\\code\\spring-flowable\\src\\main\\resources\\processes\\ask_for_overtime11.bpmn20.xml");
                // 指定文本的写出的格式：
                OutputFormat format = OutputFormat.createPrettyPrint();   //漂亮格式：有空格换行
                format.setEncoding("UTF-8");
                //1.创建写出对象
                XMLWriter writer = new XMLWriter(out, format);
                //2.写出Document对象
                writer.write(document);
                //3.关闭流
                writer.close();
            }

//    public static void read() throws IOException, DocumentException {
//        SAXReader saxReader=new SAXReader(); //SAXReader
//        Document document=saxReader.read("D:\\Users\\X.I.O\\code\\spring-flowable\\src\\main\\resources\\processes\\ask_for_overtime.bpmn20.xml");
//        Element rootElement=document.getRootElement();
//        Iterator iter=rootElement.elementIterator();
//        while(iter.hasNext()){
//            Element element=(Element)iter.next();
//            if("process".equals(element.getName())){
//                String name=element.attributeValue("name");
//                System.out.println(name);
//                Iterator process=element.elementIterator();
//                while (process.hasNext()) {
//                    Element node=(Element)process.next();
//                    if("startEvent".equals(node.getName())){
//                        String formKey=node.attributeValue("assignee");
//                    }
//                    if("sequenceFlow".equals(node.getName())){
//                        Iterator seqs=node.elementIterator();
//                        String id=node.attributeValue("id");
//                        if("sid-6cb09a5b-778a-4280-af49-9a557eba7e82".equals(id)){
//                            while (seqs.hasNext()) {
//                                Element se=(Element)seqs.next();
//                                se.setText("${checkResult=='驳回11'}");
//                                System.out.println(se.getName());
//                                System.out.println(se.getText());
//                            }
//                        }
//
//                    }
//                    System.out.println(node.getName());
//                }
//            }
//
////            // 拿到book下面的name元素对象
////
////           // Element nameElement = book.element("name");
////            while(iter2.hasNext()){
////                Element stu=(Element)iter2.next();
////                System.out.println(stu.attributeValue("formKey")+"================>");
////                System.out.println(stu.getName());
////                System.out.println(stu.attributeValue("id"));
////             //   System.out.println(stu.getStringValue());
////                System.out.println(stu.attributeValue("assignee")+";;");
////                Iterator ite3=stu.elementIterator();
////                while(ite3.hasNext()){
////                    Element st=(Element)ite3.next();
////
////                }
////            }
////            System.out.println(studentElement.attributeValue("assignee")+";;");
////            System.out.println("学号："+studentElement.attributeValue("id"));
////            System.out.println(studentElement.attributeValue("formKey"));
////            System.out.println("姓名："+studentElement.elementText("formKey"));
////            System.out.println("=========");
//        }
//    }
        }
    }
}